<template>
  <div class="comment-section">
    <!-- 添加评论表单 -->
    <div class="comment-form" v-if="userStore.user.id">
      <h3>发表评价</h3>
      <el-form
        :model="commentForm"
        :rules="commentRules"
        ref="commentFormRef"
      >
        <el-form-item prop="body">
          <el-input
            v-model="commentForm.body"
            type="textarea"
            :rows="4"
            placeholder="请输入您的课程评价..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmitComment"
            :loading="submittingComment"
          >
            发表评价
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-divider />
    
    <!-- 评论列表 -->
    <div class="comments-list">
      <h3>课程评价 ({{ comments.length }})</h3>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="comments.length === 0" class="empty-container">
        <el-empty description="暂无评价" />
      </div>
      
      <div v-else class="comments-container">
        <div 
          v-for="comment in comments" 
          :key="comment.id" 
          class="comment-item"
        >
          <div class="comment-header">
            <div class="comment-author">
              <el-avatar :size="32" :src="getAvatarUrl(comment.userid)">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="author-name">用户{{ comment.userid }}</span>
            </div>
            <span class="comment-date">{{ formatDate(comment.createTime) }}</span>
          </div>
          
          <div class="comment-content">
            <p>{{ comment.body }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { User } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import * as api from '../services/api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})

const userStore = useUserStore()
const comments = ref([])
const loading = ref(false)
const submittingComment = ref(false)
const commentFormRef = ref()

const commentForm = reactive({
  body: ''
})

const commentRules = {
  body: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 5, message: '评价内容至少5个字符', trigger: 'blur' }
  ]
}

const loadComments = async () => {
  if (!props.courseId) return
  
  try {
    loading.value = true
    const response = await api.getCommentsByCourse(props.courseId)
    comments.value = Array.isArray(response) ? response : []
  } catch (error) {
    console.error('获取评价列表失败:', error)
    ElMessage.error('获取评价列表失败')
    comments.value = []
  } finally {
    loading.value = false
  }
}

const handleSubmitComment = async () => {
  if (!commentFormRef.value) return
  
  try {
    await commentFormRef.value.validate()
    submittingComment.value = true
    
    // 额外验证
    if (!props.courseId) {
      throw new Error('课程ID无效')
    }
    
    if (!userStore.user || !userStore.user.id) {
      throw new Error('请先登录')
    }
    
    const commentData = {
      body: commentForm.body.trim(),
      userid: userStore.user.id,
      articleid: props.courseId,
      replyType: '课程'
    }
    
    console.log('准备发送的评论数据:', commentData)
    
    await api.addComment(commentData)
    
    ElMessage.success('评价发表成功')
    
    // 重置表单
    commentForm.body = ''
    commentFormRef.value.resetFields()
    
    // 重新加载评论列表
    loadComments()
    
  } catch (error) {
    console.error('发表评价失败:', error)
    ElMessage.error('发表评价失败: ' + (error.message || '未知错误'))
  } finally {
    submittingComment.value = false
  }
}

const formatDate = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(parseInt(timestamp))
  return date.toLocaleString('zh-CN')
}

const getAvatarUrl = (userId) => {
  // 生成简单的头像URL
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${userId}`
}

watch(() => props.courseId, loadComments)

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.comment-section {
  margin-top: 20px;
}

.comment-form h3,
.comments-list h3 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 15px;
}

.loading-container, .empty-container {
  padding: 40px;
  text-align: center;
}

.comments-container {
  space-y: 20px;
}

.comment-item {
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-bottom: 20px;
  background: #fafafa;
  transition: box-shadow 0.2s;
}

.comment-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-name {
  font-weight: bold;
  color: #303133;
}

.comment-date {
  font-size: 12px;
  color: #909399;
}

.comment-content p {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

.el-divider {
  margin: 30px 0;
}
</style>